package com.whiteape.book.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import com.hwangjr.rxbus.RxBus;
import com.whiteape.book.R;
import com.whiteape.book.common.RxEvent;
import com.whiteape.book.common.WaConstants;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.core.manager.ReadSettingManager;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.type.LoadFileType;
import com.whiteape.book.model.type.MediaType;
import com.whiteape.book.ui.activity.ChannelManageActivity;
import com.whiteape.book.ui.activity.FileSystemActivity;
import com.whiteape.book.ui.activity.MainActivity;
import com.whiteape.book.ui.activity.SearchActivity;
import com.whiteape.book.ui.base.BaseRVFragment;
import com.whiteape.book.ui.base.BaseTabFragment;
import com.whiteape.book.ui.guide.SimpleComponent;
import com.whiteape.book.utils.BookManager;
import com.whiteape.book.utils.FileUtils;
import com.whiteape.book.utils.MD5Utils;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.widget.guideview.Guide;
import com.whiteape.book.widget.guideview.GuideBuilder;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;

public class MediaCollectionFragment extends BaseTabFragment {

    @BindView(R.id.iv_search)
    ImageView ivSearch;

    @BindView(R.id.iv_manage_channel)
    ImageView ivManageChannel;

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    public final static int REQUEST_CODE_MANAGE_CHANNEL = 1234;
    public final static int REQUEST_CODE_ADD_LOCAL_BOOK = 2234;

    private List<Integer> channelList;

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        List<Integer> channelListInSp = ReadSettingManager.getInstance().getChannelOrder();
        if (channelListInSp == null || channelListInSp.isEmpty()) {
            channelList = new ArrayList<>(Arrays.asList(MediaType.MEDIA_TYPE_NOVEL, MediaType.MEDIA_TYPE_COMIC));
        } else {
            channelList = channelListInSp;
        }
    }

    @Override
    protected List<Fragment> createTabFragments() {
        List<Fragment> fragmentList = new ArrayList<>();
        for (int channel : channelList) {
            MediaCollectionChildFragment fragment = MediaCollectionChildFragment.newInstance(channel);
            fragmentList.add(fragment);
        }
//        MediaCollectionChildFragment novelFragment = MediaCollectionChildFragment.newInstance(MediaType.MEDIA_TYPE_NOVEL);
//        MediaCollectionChildFragment comicFragment = MediaCollectionChildFragment.newInstance(MediaType.MEDIA_TYPE_COMIC);
//        MediaCollectionChildFragment videoFragment = MediaCollectionChildFragment.newInstance(MediaType.MEDIA_TYPE_VIDEO);
//        return Arrays.asList(novelFragment, comicFragment/*, videoFragment*/);
        return fragmentList;
    }

    @Override
    protected List<String> createTabTitles() {
        List<String> titleList = new ArrayList<>();
        for (int channel : channelList) {
            titleList.add(MediaType.getName(channel));
        }
//        return Arrays.asList(getString(R.string.collection_novel),
//                getString(R.string.collection_comic)//,
////                getString(R.string.collection_video)
//        );
        return titleList;
    }

    @Override
    protected int getContentId() {
        return R.layout.fragment_collection;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        setHasOptionsMenu(true);
        if (getActivity() == null) {
            return;
        }
//        showGuideView();
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
        Objects.requireNonNull(((AppCompatActivity) getActivity()).getSupportActionBar()).setDisplayShowTitleEnabled(true);
        Objects.requireNonNull(((AppCompatActivity) getActivity()).getSupportActionBar()).setTitle("我的书架");

        toolbar.inflateMenu(R.menu.menu_media_collection);
        initReadme();

    }

    private void checkReadmeFile(){
        BookManager.createReadmeFile(getContext());
    }

    private void initReadme(){
        if(ReadSettingManager.getInstance().getReadmeInit()){
            return;
        }
        checkReadmeFile();
//        File file = new File("");
        File file = BookManager.getReadmeFile();
        if(!file.exists()){
            BookManager.createReadmeFile(getContext());
        }
        //再次检测还没有的话
        if(!file.exists()){
            return;
        }
        CollectionMediaBean collectionMediaBean = convertFileToBook(file);
        MediaStorageManager.getInstance().saveCollectionMedia(collectionMediaBean);
        RxBus.get().post(RxEvent.MEDIA_COLLECTION_ADD, collectionMediaBean);
        ReadSettingManager.getInstance().setReadmeInit(true);
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.menu_media_collection, menu);
        menu.findItem(R.id.action_auto_update_catalog).setChecked(ReadSettingManager.getInstance().getCollMediaAutoUpdateCatalog());
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        switch (id){
            case R.id.action_add:
                startActivityForResult(new Intent(getContext(), FileSystemActivity.class)
                        .putExtra(FileSystemActivity.FILE_TYPE_KEY, LoadFileType.FILE_TYPE_BOOK), REQUEST_CODE_ADD_LOCAL_BOOK);
                break;
            case R.id.action_change_order:
                startActivityForResult(new Intent(getContext(), ChannelManageActivity.class)
                                .putStringArrayListExtra("channelList", new ArrayList<>(createTabTitles())),
                        REQUEST_CODE_MANAGE_CHANNEL);
                break;
            case R.id.action_arrange:
                ((MediaCollectionChildFragment)getCurrentFragment()).performBatchAction();
                break;

            case R.id.action_search:

                startActivity(new Intent(getContext(), SearchActivity.class)
                        .putExtra(SearchActivity.INPUT_EXTRA_MEDIA_TYPE, ((MediaCollectionChildFragment) getCurrentFragment()).getMediaType()));
                        break;
            case R.id.action_auto_update_catalog:
                boolean isChecked = !item.isChecked();
                item.setChecked(isChecked);
                ReadSettingManager.getInstance().setCollMediaAutoUpdateCatalog(isChecked);
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    private void showGuideView() {

        GuideBuilder builder = new GuideBuilder();
        builder.setTargetView(ivSearch)
                .setAlpha(150)
                .setHighTargetCorner(20)
                .setHighTargetPadding(10);
        builder.setOnVisibilityChangedListener(new GuideBuilder.OnVisibilityChangedListener() {
            @Override
            public void onShown() {
            }

            @Override
            public void onDismiss() {
//                    showGuideView2();
            }
        });

        builder.addComponent(new SimpleComponent());
        Guide guide = builder.createGuide();
        guide.show(getActivity());
    }

//    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//        if (!hidden) {
//            showGuideView();
//        }
//    }

    @Override
    protected void initEvent() {
        super.initEvent();

        ivSearch.setOnClickListener(v ->
                startActivity(new Intent(getContext(), SearchActivity.class)
                .putExtra(SearchActivity.INPUT_EXTRA_MEDIA_TYPE, ((MediaCollectionChildFragment) getCurrentFragment()).getMediaType())

        ));
        ivManageChannel.setOnClickListener(v -> {

        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Fragment fragment = getCurrentFragment();
        if (fragment instanceof BaseRVFragment) {
            if (((BaseRVFragment) fragment).onKeyDown(keyCode, event)) {
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_CODE_MANAGE_CHANNEL) {
            if (data != null && data.hasExtra("channelList")) {
                List<String> channelNameList = data.getStringArrayListExtra("channelList");
                channelList.clear();
                for (String channelName : channelNameList) {
                    channelList.add(MediaType.getMediaType(channelName));
                }
                ReadSettingManager.getInstance().setChannelOrder(channelList);
            }
            resetViewPager();
        }else if(requestCode == REQUEST_CODE_ADD_LOCAL_BOOK){

            List<File> files = (List<File>)data.getSerializableExtra("data");
            List<CollectionMediaBean> beans = convertCollBook(files);
            if(beans != null && beans.size() > 0) {
                MediaStorageManager.getInstance().saveCollectionMedia(beans.get(0));
                RxBus.get().post(RxEvent.MEDIA_COLLECTION_ADD, beans.get(0));
            }
        }
    }

    private List<CollectionMediaBean> convertCollBook(List<File> files) {
        List<CollectionMediaBean> collBooks = new ArrayList<>(files.size());
        for (File file : files) {
            //判断文件是否存在
            if (!file.exists()) continue;

            CollectionMediaBean collBook = convertFileToBook(file);
            collBooks.add(collBook);
        }
        return collBooks;
    }

    private CollectionMediaBean convertFileToBook(File file){
        CollectionMediaBean collBook = new CollectionMediaBean();
        collBook.setId(MD5Utils.strToMd5By16(file.getAbsolutePath()));
        collBook.setBookSourceUrl(file.getAbsolutePath());
        collBook.setTitle(file.getName().replace(".txt", ""));
        collBook.setAuthor("");
//            collBook.setShortIntro("无");
//            collBook.setCover(file.getAbsolutePath());
        collBook.setIfLocal(true);
        collBook.setMediaType(MediaType.MEDIA_TYPE_NOVEL);
        collBook.setLastChapter("开始阅读");
        collBook.setLastUpdated(StringUtils.dateConvert(file.lastModified(), WaConstants.FORMAT_BOOK_DATE));
        collBook.setLastRead(StringUtils.
                dateConvert(System.currentTimeMillis(), WaConstants.FORMAT_BOOK_DATE));
        return collBook;
    }

}
